<template>
    <div class="background">
        <div class="container">
            <div>
                <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
                    <el-tab-pane v-for="category in categoryList" :key="category.categoryId" :label="category.categoryName" :name="String(category.categoryId)">
                        <DeviceCard :deviceList="deviceList" showType="card"></DeviceCard>
                    </el-tab-pane>
                    <div style="margin-left: 15px; margin-bottom: 15px" v-if="deviceList.length == 0">{{ $t('noData') }}</div>
                    <div class="el-page" v-if="deviceList.length > 0" style="float: right; margin-right: 10px; margin-bottom: 5px">
                        <el-pagination
                            @size-change="handleSizeChange"
                            @current-change="handleCurrentChange"
                            :current-page="page"
                            :page-sizes="[10, 20, 30, 50]"
                            :page-size="pageSize"
                            layout="total, sizes, prev, pager, next, jumper"
                            :total="total"
                        ></el-pagination>
                    </div>
                </el-tabs>
            </div>
        </div>
    </div>
</template>

<script>
import { getDeviceList, getCategoryList } from '@/api/private/equipmentMonitoring.js';
import DeviceCard from './components/configuration/deviceCard.vue';
export default {
    name: 'equipmentMonitoring',
    //注册组件
    components: { DeviceCard },
    data() {
        return {
            activeName: '1',
            showType: 'card',
            deviceList: [],
            categoryList: [], // 存储分类数据
            total: 0,
            page: 1,
            pageSize: 10,
        };
    },
    mounted() {
        // 组件挂载时检查路由参数并跳转到对应标签
        this.handleRouteQuery();
        // 获取分类列表数据
        this.getList();
    },
    watch: {
        // 监听路由参数变化
        '$route.query': {
            handler() {
                this.handleRouteQuery();
            },
            immediate: true,
        },
    },
    methods: {
        // 核心处理方法：先等 getList 完成，再安全赋值
        async handleRouteQuery() {
            const { categoryId: queryCategoryId } = this.$route.query || {}; // 容错：query 可能为空
            // 1. 先等待 getList 完成，确保 categoryList 有数据（或为空数组）
            await this.getList();
            // 2. 判断 categoryList 是否有数据，再处理 activeName
            if (this.categoryList.length > 0) {
                // 有参数则用参数，无参数则用第一个元素的 categoryId
                this.activeName = queryCategoryId ? queryCategoryId.toString() : this.categoryList[0].categoryId.toString();
                // 3. 传参给 getDeviceData（注意：无参数时传 undefined 或第一个 categoryId，根据需求调整）
                this.getDeviceData(queryCategoryId || this.categoryList[0].categoryId);
            } else {
                // 容错：如果 categoryList 为空，给 activeName 设默认值（如空字符串）
                this.activeName = '';
                this.getDeviceData(null); // 无数据时传空，避免 getDeviceData 报错
            }
        },
        // 标签点击处理
        handleClick(tab) {
            this.activeName = tab.name;
            this.page = 1;
            this.pageSize = 10;
            this.getDeviceData(Number(tab.name));
        },
        // 获取设备列表数据
        async getDeviceData(categoryId) {
            try {
                this.loading = true;
                // console.log('查询数据:', categoryId, this.page, this.pageSize);
                const response = await getDeviceList(categoryId, this.page, this.pageSize);
                // console.log('响应数据:', response);
                if (response.code === 200) {
                    this.deviceList = response.rows;
                    this.total = response.total;
                    // console.log('设备列表:', this.deviceList);
                }
            } catch (error) {
                console.error('获取设备列表失败:', error);
                this.deviceList = [];
            } finally {
                this.loading = false;
            }
        },
        //获取设备分类列表
        // getList() {
        //     getCategoryList().then((response) => {
        //         console.log(response);
        //         if (response.code === 200) {
        //             this.categoryList = response.data;
        //         }
        //     });
        // },
        getList() {
            // 返回 Promise，让调用方可以等待请求完成
            return new Promise((resolve) => {
                // 替换成你的实际请求逻辑（如 axios）
                getCategoryList()
                    .then((res) => {
                        // this.categoryList = res.data; // 给 categoryList 赋值
                        // 按照 orderNum 从小到大排序后给 categoryList 赋值
                        this.categoryList = res.data.sort((a, b) => a.orderNum - b.orderNum);
                        resolve(); // 通知请求完成
                    })
                    .catch(() => {
                        this.categoryList = []; // 出错时兜底为空数组
                        resolve();
                    });
            });
        },
        //切换当前页面
        handleCurrentChange(val) {
            this.page = val;
            this.getDeviceData(this.activeName);
        },
        //切换每页显示个数
        handleSizeChange(val) {
            this.pageSize = val;
            this.getDeviceData(this.activeName);
        },
    },
};
</script>

<style lang="scss" scoped>
.background {
    background-color: rgba(0, 11, 61, 0.79);
    min-height: calc(100vh - (72 / 1080 * 100vh));
    padding: 10px;
}
.container {
    width: 100%;
    background-color: rgba(0, 11, 61, 0.79);
    padding: 10px;
    border-radius: 8px;
    border-width: #{px2vw(1)};
    border-style: solid;
    // 渐变边框背景（核心样式，颜色部分无需转换）
    border-image: linear-gradient(180deg, rgba(22, 93, 255, 0), rgba(22, 93, 255, 0.59), rgba(22, 93, 255, 1)) 1 1;
}

.el-tabs {
    color: white;
}
::v-deep .el-tabs__item {
    color: white;
}
/* 选项 */
::v-deep .el-tabs__item.is-top {
    height: 32px;
    line-height: 34px;
    margin-bottom: 15px;
    margin-top: 15px;
    border: none !important;
    border-radius: 5px;
    color: white;
}
::v-deep .el-tabs__item.is-top.is-active {
    background-color: #486ff2;
}
::v-deep .el-tabs__nav.is-top {
    border: none !important;
}
/* 边界线 */
::v-deep .el-tabs--card .el-tabs__header {
    border-width: 2px;
}
::v-deep .el-page {
    .el-input__inner {
        color: #fff;
        background-color: #0b1645;
        border-color: #486ff2;
    }
    .el-pagination__total {
        color: #fff;
    }
    .el-pagination__jump {
        color: #fff;
    }
    .el-pager li {
        margin-right: 5px;
        margin-left: 5px;
        background-color: #1a2552 !important;
        color: #fff !important;
        border-radius: 3px;
        // border: 1px solid #486ff2;
    }
    // .el-pager li:hover {
    //     background-color: #7a96f3 !important;
    //     color: #fff !important;
    //     border: 1px solid #486ff2;
    // }
    .el-pager li.active {
        background-color: #409eff !important;
    }
    .el-pagination button {
        margin-right: 5px;
        margin-left: 5px;
        color: #fff;
        background-color: #1a2451 !important;
        // border: 1px solid #486ff2;
    }
}
</style>
